package com.example.sfm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.sfm.pojo.dto.CodeDto;
import com.example.sfm.properties.CaptchaProperties;
import com.example.sfm.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;


@Slf4j
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor
@Tag(name = "验证码接口")
public class CaptchaController {

    private final CaptchaProperties captchaProperties;

    @GetMapping("/getCaptcha")
    @Operation(summary = "获取验证码", description = "生成验证码图片并返回给前端")
    public Result<?> getCaptcha(@NotNull HttpSession session, @NotNull HttpServletResponse response) {
        log.info("开始生成验证码...");
        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        // 设置返回数据类型
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 将生成的验证码和验证码生成时间存储到session中
            session.setAttribute("captcha", lineCaptcha.getCode());
            session.setAttribute("date", new Date());
            response.getOutputStream().close();
            return Result.success("获取验证码成功");
        } catch (IOException e) {
            log.error("验证码生成失败", e);
            return Result.error(400, "验证码生成失败");
        }
    }

    @PostMapping("/check")
    @Operation(summary = "校验验证码", description = "校验用户输入的验证码是否正确")
    public Result<?> checkCaptcha(@RequestBody @NotNull CodeDto codeDto, HttpSession session) {
        log.info("接收到验证码: {}", codeDto.getCode());

        if (!StringUtils.hasLength(codeDto.getCode())) {
            return Result.success(false, "验证码不能为空");
        }

        // 从session中获取之前生成的验证码
        String code = (String) session.getAttribute("captcha");
        Date createTime = (Date) session.getAttribute("date");

        if (code == null) {
            return Result.success(false, "验证码已过期，请重新获取");
        }

        // 校验验证码
        if (codeDto.getCode().equalsIgnoreCase(code)) {
            // 验证码是否过期
            boolean isNotExpired = createTime != null && System.currentTimeMillis() - createTime.getTime() <= captchaProperties.getTime();
            if (isNotExpired) {
                return Result.success(true, "验证码校验成功");
            } else {
                return Result.success(false, "验证码已过期");
            }
        }

        return Result.success(false, "验证码不正确");
    }
}



